<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="主办人姓名" prop="hostName">
        <el-input
          v-model="queryParams.hostName"
          placeholder="请输入主办人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="举办地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入举办地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="桌数" prop="tableCount">
        <el-input
          v-model="queryParams.tableCount"
          placeholder="请输入桌数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="举办日期" prop="eventDate">
        <el-date-picker clearable
                        v-model="queryParams.eventDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择举办日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="banquetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="宴席类型" align="center" prop="banquetType">
        <template slot-scope="scope">
          {{ banquetTypeMap[scope.row.banquetType] || '未知类型' }}
        </template>
      </el-table-column>
      <el-table-column label="主办人姓名" align="center" prop="hostName"/>
      <el-table-column label="举办地点" align="center" prop="location"/>
      <el-table-column label="桌数" align="center" prop="tableCount"/>
      <el-table-column label="举办日期" align="center" prop="eventDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.eventDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" prop="contactPhone"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="宴席类型" prop="banquetType">
          <el-select
            v-model="form.banquetType"
            placeholder="请选择宴席类型"
            filterable
            clearable
            style="width: 100%"
            value-key="value"
          >
            <el-option
              v-for="item in banquetOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="主办人姓名" prop="hostName">
          <el-input v-model="form.hostName" placeholder="请输入主办人姓名"/>
        </el-form-item>
        <el-form-item label="举办地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入举办地点"/>
        </el-form-item>
        <el-form-item label="桌数" prop="tableCount">
          <el-input v-model="form.tableCount" placeholder="请输入桌数" type="number"
                    :min="1" @keypress.native="handleNumberInput"/>
        </el-form-item>
        <el-form-item label="举办日期" prop="eventDate">
          <el-date-picker clearable
                          v-model="form.eventDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择举办日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listBanquet, getBanquet, delBanquet, addBanquet, updateBanquet} from "@/api/catering/banquet";

export default {
  name: "Banquet",
  data() {
    // 自定义验证规则
    const validateTableCount = (rule, value, callback) => {
      const num = Number(value);
      if (isNaN(num)) {
        callback(new Error('请输入有效数字'));
      } else if (num <= 0) {
        callback(new Error('必须大于0'));
      } else if (!Number.isInteger(num)) {
        callback(new Error('必须输入整数'));
      } else {
        callback();
      }
    };
    return {
      banquetOptions: [
        {value: '1', label: '婚宴'},
        {value: '2', label: '满月宴'},
        {value: '3', label: '百日宴'},
        {value: '4', label: '生日宴'},
        {value: '5', label: '商务宴请'},
        {value: '6', label: '家庭聚会'},
        {value: '7', label: '同学聚会'},
        {value: '8', label: '周年庆典'},
        {value: '9', label: '其他类型'}
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      banquetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        banquetType: null,
        hostName: null,
        location: null,
        tableCount: null,
        eventDate: null,
        contactPhone: null,
        isDeleted: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hostName: [
          {required: true, message: "主办人姓名不能为空", trigger: "blur"}
        ],
        tableCount: [
          {required: true, validator: validateTableCount, trigger: ['blur', 'change']}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    // 创建宴会类型映射表
    banquetTypeMap() {
      return this.banquetOptions.reduce((acc, cur) => {
        acc[cur.value] = cur.label
        return acc
      }, {})
    }
  },
  methods: {
    // 输入过滤方法
    handleNumberInput(event) {
      const allowedKeys = ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab'];
      if (allowedKeys.includes(event.key)) return;
      if (!/[0-9]/.test(event.key)) {
        event.preventDefault();
      }
    }
    ,
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listBanquet(this.queryParams).then(response => {
        this.banquetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    }
    ,
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    }
    ,
    // 表单重置
    reset() {
      this.form = {
        id: null,
        banquetType: null,
        hostName: null,
        location: null,
        tableCount: null,
        eventDate: null,
        contactPhone: null,
        isDeleted: null,
        createdBy: null,
        createdAt: null,
        updatedBy: null,
        updatedAt: null
      };
      this.resetForm("form");
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加宴席信息";
    }
    ,
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBanquet(id).then(response => {
        const rawData = response.data;
        this.form = {
          ...rawData,
          banquetType: rawData.banquetType?.toString() // 确保类型匹配
        };
        this.open = true;
        this.title = "修改宴席信息";
      });
    }
    ,
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBanquet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanquet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？').then(function () {
        return delBanquet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/banquet/export', {
        ...this.queryParams
      }, `banquet_${new Date().getTime()}.xlsx`)
    }
  }
}
;
</script>
